using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 基于Json配置文件的配置管理器
/// </summary>
public class ConfigManagerByJson : IConfigManager
{
    //保存键值对应用设置集合
    private static Dictionary<string,string> _AppSetting;
    
    /// <summary>
    /// 只读属性得到应用设置(键值对集合)
    /// </summary>
    public Dictionary<string, string> AppSetting
    {
        get { return _AppSetting; }
    }

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="jsonPath">Json配置文件路径</param>
    public ConfigManagerByJson(string jsonPath)
    {
        _AppSetting = new Dictionary<string, string>();
        //初始化解析Json数据，加载到集合中
        InitAndAnalysisJson(jsonPath);
    }
    
    /// <summary>
    /// 得到AppSetting的最大数值
    /// </summary>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public int GetAppSettingMaxNumber()
    {
        if (_AppSetting.Count != null && _AppSetting.Count >= 1)
        {
            return AppSetting.Count;
        }
        else
        {
            return 0;
        }
    }

    //初始化解析Json数据，加载到集合中
    private void InitAndAnalysisJson(string jsonPath)
    {
        TextAsset configInfo = null;
        KeyValueInfo keyValueInfoObj = null;

        if (string.IsNullOrEmpty(jsonPath)) { return; }

        try
        {
            configInfo = Resources.Load<TextAsset>(jsonPath);
            keyValueInfoObj = JsonUtility.FromJson<KeyValueInfo>(configInfo.text);
        }
        catch
        {
            //自定义异常
            throw new JsonAnalysisException(GetType()+"/InitAndAnalysisJson()/Json Analysis Exception ! Parameter jsonPath = " + jsonPath);
        }

        foreach (KeyValueNode nodeInfo in keyValueInfoObj.ConfigInfo)
        {
            _AppSetting.Add(nodeInfo.key,nodeInfo.value);
        }
    }
}
